package nio.example.study.client.codec.dispatcher;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import nio.example.study.common.RequestMessage;
import nio.example.study.common.keepalive.KeepaliveOperation;
import nio.example.study.util.IdUtil;

@Slf4j
@ChannelHandler.Sharable
public class KeepaliveHandler extends ChannelDuplexHandler {

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

		if(evt == IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT) {
			log.info("write idle happen. so need to send keepalive to keep connnection not closed by server");
			KeepaliveOperation keepaliveOperation = new KeepaliveOperation();
			RequestMessage requestMessage = new RequestMessage(IdUtil.nextId(), keepaliveOperation);
			ctx.writeAndFlush(requestMessage);
		}
		super.userEventTriggered(ctx, evt);
	}
}
